package com.example.demo.service.impl;

import com.example.demo.mapper.AdMapper;
import com.example.demo.mapper.entity.*;
import com.example.demo.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lucy
 * @create 2024-03-14 0:33
 */
@Service
public class AdServiceImpl implements AdService {

    @Autowired
    private AdMapper mapper;
    @Override
    public List<Ad> getAdList() {
        return mapper.getAdList();
    }

    @Override
    public Ad selectAdById(int adId) {
        return mapper.selectAdById(adId);
    }

    @Override
    public AdSetting selectSetting() {
        return mapper.selectSetting();
    }

    @Override
    public void insertAdClick(AdClick adClick) {
        mapper.insertAdClick(adClick);
    }

    @Override
    public void insertAdTransaction(AdTransaction transaction) {
        mapper.insertAdTransaction(transaction);
    }

    @Override
    public void updateAderBalance(Advertiser advertiser, double clickCost) {
        while(true){
            int currentVersion = advertiser.getVersion(); // 获取当前版本号
            int updatedRows = mapper.deductClickCost(advertiser.getAdvertiserId(), clickCost, currentVersion); // 尝试更新并返回受影响的行数
            if (updatedRows > 0) {
                double balance = advertiser.getBalance();
                if(balance < 0){
                    mapper.updateAdStatus(advertiser.getAdvertiserId(), 3);
                }
                return; // 更新成功
            } else {
                advertiser = mapper.selectAdvertiserById(advertiser.getAdvertiserId());// 获取最新商家余额信息
            }
        }
    }

    @Override
    public Advertiser selectAdvertiserById(int advertiserId) {
        return mapper.selectAdvertiserById(advertiserId);
    }

    @Override
    public List<AdClick> selectAllAdClick() {
        return mapper.selectAllAdClick();
    }

    @Override
    public Student selectStudentById(int studentId) {
        return mapper.selectStudentById(studentId);
    }

    @Override
    public int selectStudentCountByGender(int gender) {
        return mapper.selectStudentCountByGender(gender);
    }

    @Override
    public int selectStudentCountByNativePlace(int nativePlace) {
        return mapper.selectStudentCountByNativePlace(nativePlace);
    }

    @Override
    public int selectStudentCountByCollege(int collegeId) {
        return mapper.selectStudentCountByCollege(collegeId);
    }

    @Override
    public List<AdKey> selectAllAdKey() {
        return mapper.selectAllAdKey();
    }

    @Override
    public AdKey selectAdKeyById(int adId) {
        return mapper.selectAdKeyById(adId);
    }

    @Override
    public List<AdStudent> selectAdStudent(int studentId) {
        return mapper.selectAdStudent(studentId);
    }
}
